package is.ru.honn.rumblr.factory;

import is.ru.honn.rumblr.data.PostDetail;
import is.ru.honn.rumblr.domain.AbstractRumblrPost;
import is.ru.honn.rumblr.domain.LinkPost;
import is.ru.honn.rumblr.domain.RumblrPost;
import is.ru.honn.rumblr.util.XmlUtil;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class LinkPostFactory extends PostFactory
{
  @Override
  public RumblrPost createPostFromXML(Element e)
  {
    LinkPost post = new LinkPost();
    createHeader(post, e);
    post.setLinkUrl(XmlUtil.getXPathValue(e, "link-url"));
		post.setLinkText(XmlUtil.getXPathValue(e, "link-text"));
    return post;
  }

  //Creates a list of postDetails for a Linked post(url,text and tags) and returns it.
  @Override
  public List<PostDetail> createPostDetails(AbstractRumblrPost post)
  {
      LinkPost link = (LinkPost)post;
      List<String> tags = link.getTags();
      List<PostDetail> postDetails = new ArrayList<PostDetail>();
      PostDetail postDetail;

      postDetail = new PostDetail(link.getId(), "link-url", link.getLinkUrl());
      postDetails.add(postDetail);
      postDetail = new PostDetail(link.getId(), "link-text", link.getLinkText());
      postDetails.add(postDetail);

      for (String tag: tags)
      {
          postDetail = new PostDetail(link.getId(), "tag", tag);
          postDetails.add(postDetail);
      }

      return postDetails;
  }

  //Creates a Link post sets it type and returns it, createPostFromType from postfactory calls this function
  @Override
  public AbstractRumblrPost createPostType(String type)
  {
      LinkPost link = new LinkPost();
      link.setType(type);       // Sets the type post
      return link;
  }


  @Override
  public  AbstractRumblrPost mergeDetailsWithPost(AbstractRumblrPost post, Collection<PostDetail> details)
  {
      LinkPost link = (LinkPost)post;
      List<String> tags = new ArrayList<String>();

      for(PostDetail dt : details)
      {
          if (dt.getName().equals("link-text"))
          {
            link.setLinkText(dt.getValue());
          }
          else if (dt.getName().equals("link-url"))
          {
              link.setLinkUrl(dt.getValue());
          }
          else if (dt.getName().equals("tag"))
          {
              tags.add(dt.getValue());
          }

      }
      link.addTags(tags);

      return link;
  }
}
